/*
 * Copyright (C) 2019-2020 Alibaba Group Holding Limited
 */

/******************************************************************************
 * @file     board_init.c
 * @brief    CSI Source File for board init
 * @version  V1.0
 * @date     31. June 2018
 ******************************************************************************/
#include <stdio.h>
#include <stdint.h>

#include <soc.h>
#include <csi_core.h>
#include <silan_syscfg.h>

#include <drv/usart.h>
#include <drv/gpio.h>
#include <pin_name.h>
#include <pinmux.h>
#include <syscfg.h>

#include "board.h"

extern void ioreuse_initial(void);
static void board_pinmux_config(void)
{
    //console
    drv_pinmux_config(CONSOLE_TXD, CONSOLE_TXD_FUNC);
    drv_pinmux_config(CONSOLE_RXD, CONSOLE_RXD_FUNC);

    // BT
    drv_pinmux_config(BT_UART_TXD, BT_UART_TXD_FUNC);
    drv_pinmux_config(BT_UART_RXD, BT_UART_RXD_FUNC);

    //WiFi
    drv_pinmux_config(WIFI_SD_DAT0, WIFI_SD_DAT0_FUNC);
    drv_pinmux_config(WIFI_SD_DAT1, WIFI_SD_DAT1_FUNC);
    drv_pinmux_config(WIFI_SD_DAT2, WIFI_SD_DAT2_FUNC);
    drv_pinmux_config(WIFI_SD_DAT3, WIFI_SD_DAT3_FUNC);
    drv_pinmux_config(WIFI_SD_CLK, WIFI_SD_CLK_FUNC);
    drv_pinmux_config(WIFI_SD_CMD, WIFI_SD_CMD_FUNC);

    //SD card
    drv_pinmux_config(TF_SDIO_DAT0, TF_SDIO_DAT0_FUNC);
    drv_pinmux_config(TF_SDIO_DAT1, TF_SDIO_DAT1_FUNC);
    drv_pinmux_config(TF_SDIO_SCL, TF_SDIO_SCL_FUNC);
    drv_pinmux_config(TF_SDIO_SDA, TF_SDIO_SDA_FUNC);
    drv_pinmux_config(TF_SDIO_CLK, TF_SDIO_CLK_FUNC);
    drv_pinmux_config(TF_SDIO_CMD, TF_SDIO_CMD_FUNC);

    drv_pinmux_config(PB4, PB4_PCM_I2S_SCLK);
    drv_pinmux_config(PB5, PB5_PCM_I2S_WS);
    // drv_pinmux_config(PB6, PB6_PCM_I2S_SDI);
    drv_pinmux_config(PB7, PB7_PCM_I2S_SDO);

    silan_syscfg_reg_t *syscfg = (silan_syscfg_reg_t *)SILAN_SYSCFG_BASE;
    /* tf sdio 4 mA */
    syscfg->CTR_PAD6 |= 1 << 19;
    syscfg->CTR_PAD6 |= 1 << 27;
    syscfg->CTR_PAD7 |= 1 << 3;

    /* wifi sdio 4 mA PC1~6 */
    syscfg->CTR_PAD4 |= 1 << 19;
    syscfg->CTR_PAD4 |= 1 << 27;
    syscfg->CTR_PAD5 |= 1 << 3;
    syscfg->CTR_PAD5 |= 1 << 19;
    syscfg->CTR_PAD5 |= 1 << 27;
    
    syscfg->CTR_PAD1 &= ~(1 << 13);
}

static void wifi_power_enable(int enable)
{
    static gpio_pin_handle_t     power_pin;
    drv_pinmux_config(WLAN_POWER_PIN, PIN_FUNC_GPIO);
    power_pin = csi_gpio_pin_initialize(WLAN_POWER_PIN, NULL);
    csi_gpio_pin_config_mode(power_pin, GPIO_MODE_PUSH_PULL);
    csi_gpio_pin_config_direction(power_pin, GPIO_DIRECTION_OUTPUT);
    csi_gpio_pin_write(power_pin, enable);
    aos_msleep(200);
}

void board_init(void)
{
    ioreuse_initial();

    board_pinmux_config();

    wifi_power_enable(1);

    /* close m0/dsp debug */
    silan_mcu_debug_close();
    silan_dsp_debug_close();
}
